<template>
    <div class="gee">
        <div style="height: 60%;background-color: #B3C0D1;color: #333;padding: 0px 10px;margin-top: -5px">
            <el-row :gutter="10" id="top">
                <el-col :span="6" style="justify-content: space-around">
                    <div class="grid-content1">
                        <el-tabs v-model="activeName" @tab-click="handleClick">
                            <el-tab-pane label="数据" name="first">
                                <el-tree
                                        class="node"
                                        :data="dataOptions"
                                        :props="defaultProps"
                                        @node-click="handleNodeClick">
                                </el-tree>
                            </el-tab-pane>
                            <el-tab-pane label="模型" name="second">
                                <el-tree
                                        :data="modelOptions"
                                        :props="defaultProps"
                                        node-key="label"
                                        @node-click="handleNodeClick"
                                        ref="tree">
                                </el-tree>
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                </el-col>
                <el-col :span="11" style="justify-content: space-around">
                    <div class="grid-content2">
                        <div class="workspace">
                            <div class="flowchart-demo" id="flowchart-demo"></div>
                            <el-button class="butt" id="cleanbtn" style="right:12%" type="primary" @click="cleanFlow">
                                清除
                            </el-button>
                            <el-button class="butt" id="runbtn" style="right:1%" type="success" @click="runFlow">运行
                            </el-button>
                        </div>
                    </div>
                </el-col>
                <el-col :span="7" style="justify-content: space-around">
                    <div class="grid-content3">
                        <el-row>
                            <gee-table :tableData="tableData" :dagId="dagId" v-on:addGeeMap="addGeeMap"></gee-table>
                        </el-row>
                    </div>
                </el-col>
            </el-row>
        </div>
        <div style="height: 40%;width:100%;background-color: #ffffff;color: #333;text-align: center;position:absolute">
            <div id="map1" ref="map" class="map-div" style="width: 100%"></div>
        </div>
        <v_position :position-visible="positionVisible"></v_position>
        <modelDialog :currentPage="page" v-on:totalModelParam="getTotalParam"></modelDialog>
        <dataPreviewDialog :currentPage="page"></dataPreviewDialog>
    </div>
</template>

<script>
    import geeTable from '../../components/table/geeTable'
    import dataDialog from "../../components/dialog/dataDialog"
    import dataPagination from "../../components/pagination/dataPagination"
    import modelDialog from '../../components/dialog/modelDialog'
    import mapDiv from '../../components/div/mapDiv'
    import positionDialog from '../../components/dialog/positionDialog';
    import dataPreviewDialog from '../../components/dialog/dataPreviewDialog';

    import "openlayers/dist/ol-debug.js";
    import jsplumb from "jsplumb";

    let source = new ol.source.Vector({wrapX: false});
    let vector = new ol.layer.Vector({
        source: source
    });
    export default {
        name: "GEE",
        components: {
            "gee-table": geeTable,
            "map-div": mapDiv,
            "data-pagination": dataPagination,
            "modelDialog": modelDialog,
            "v_position": positionDialog,
            "dataPreviewDialog": dataPreviewDialog,
        },
        data() {
            return {
                tableData: '',
                dagId:[],
                selectedTab: 0,
                totalModelParam: [],
                page: '',
                maxIn: -1,
                positionVisible: {
                    v: false
                },
                dialogVisible: {
                    v: false,
                },
                previewDialogVisible:{
                    v:false
                },
                artifactId: '',
                j_instance: "",
                activeName: 'first',
                modelOptions: [{
                    value: 'all',
                    label: '全部模型',
                    children: [{label: 'BKmeans'}]
                }],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                dataOptions: [{
                    value: 'Public',
                    label: '公共数据',
                    children: [],
                },
                    {
                        value: 'Personal',
                        label: '我的数据',
                        children: [],
                    }]
            }
        },
        methods: {
            handleClick(tab, event) {
                this.selectedTab = tab.index;
            },
            refresh() {
                this.$refs.allprojectTable.task = [];
                this.$refs.allprojectTable.getProjectData();
            },
            handleNodeClick(data) {
                document.onmouseup = function (e) {
                    $(".el-tabs__content").css("overflow-y", "auto");
                };
                document.onmousedown = function (e) {
                    $(".el-tabs__content").css("overflow-y", "hidden");
                };
                $("div[class='el-tree-node__children'] span[class='el-tree-node__label']").addClass("drahitem");
                $(".drahitem").draggable({
                    scope: "inputnodes",
                    helper: function () {
                        let clone = $('<div class="ui-clone">' + $(this).html() + '</div>');
                        clone.appendTo('body');
                        return clone;
                    },
                    containment: 'body',
                    appendTo: 'body'
                    // scope: "inputnodes",
                    // helper: "clone",
                    // containment: $("#flowchart-demo")
                });
            },
            showModelData() {
                let obj = this;
                this.$axios.get(
                    // params:{ userid: "userid"},
                    //  'http://192.168.240.25:3000/dldsj/parallel/get',
                    '/parallel/get')
                    .then(res => {
                        let options = [];
                        for (let modelItem of res.body) {
                            let option = {};
                            option.value = modelItem.artifactId;
                            option.label = modelItem.artifactId;
                            options.push(option);
                        }
                        obj.modelOptions[0].children = options;
                    }).catch(function () {
                    console.log(error);
                })
            },
            showTable() {
                let that = this;
                this.$axios.get('/data/list?offset=0&size=12')
                    .then(function (res) {
                        if (res.code === 200) {
                            let result = res.body.data;
                            let options = [];
                            for (let i = 0; i < result.length; i++) {
                                let option = {};
                                option.value = result[i].data.pk_meta_id;
                                option.label = result[i].data.meta_name;
                                options.push(option);
                                that.option = option;
                            }
                            that.dataOptions[0].children = options;
                        } else {
                            alert(res.message);
                        }
                    }).catch(function (err) {
                    console.log(err);
                })
            },
            showMyData() {
                let that = this;
                this.$axios.get('/user/data?offset=0&size=100')
                    .then(function (res) {
                        let result = res.body.data;
                        let options = [];
                        for (let i = 0; i < result.length; i++) {
                            let option = {};
                            option.value = result[i].data.name;
                            option.label = result[i].data.name;
                            options.push(option);
                            that.option = option;
                        }
                        that.dataOptions[1].children = options;
                    }).catch(function (err) {
                    console.log(err);
                })
            },
            getTotalParam(data) {
                console.log(data);
                this.totalModelParam.push(data);
            },
            mapInit() {
                this.$nextTick(function () {
                    let that = this;
                    that.$refs.map.innerText = null;
                    let gaode_layer = new ol.layer.Tile({
                        source: new ol.source.XYZ({
                            url: 'http://webrd03.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8'
                        }),
                        projection: 'EPSG:3857'
                    });
                    that.map = new ol.Map({
                        target: 'map1',
                        layers: [gaode_layer, vector],
                        view: new ol.View({
                            center: ol.proj.transform([116.4, 39.7], 'EPSG:4326', 'EPSG:3857'),//初始化中心为北京
                            zoom: 10,
                            minZoom: 3,
                            maxZoom: 18
                        }),
                        controls: ol.control.defaults({
                            attributionOptions: {collapsible: false},
                            rotateOptions: {className: 'custom-rotate'}
                        }).extend([
                            new ol.control.OverviewMap({
                                collapsible: false,
                                collapsed: false,
                                className: 'custom-overview-map'
                            }),
                            new ol.control.ScaleLine({units: 'metric'}),
                            new ol.control.FullScreen({className: 'custom-fullscreen'}),
                            new ol.control.MousePosition({
                                coordinateFormat: ol.coordinate.createStringXY(4),
                                projection: 'EPSG:4326',
                                className: 'custom-mouse-position'
                            })
                        ]),
                        logo: false
                    }); //Map初始化
                    //去掉鹰眼的放大缩小按钮
                    that.map.controls.array_[3].element.lastElementChild.style.display = "none";
                })
            },
            cleanFlow() {
                let nodes = document.getElementById("flowchart-demo").children;
                let nodesId = [];
                for (let i = 0; i < nodes.length; i++) {
                    nodesId.push(nodes[i].id);
                }
                for (let i = 0; i < nodesId.length; i++) {
                    this.j_instance.remove(nodesId[i]);
                }
                // this.tableData = '';
            },
            runFlow() {
                // this.tableData = [];
                let linelist = this.j_instance.getAllConnections();
                // let inputData = [];
                let methodUseId = [];
                let methodUse = [];
                for (let listItem of linelist) {
                    //拼接输入的数据
                    // if (listItem.source.className.indexOf('first') !== -1) {
                    //     if (inputData.indexOf(listItem.source.innerText) === -1)
                    //         inputData.push(listItem.source.innerText);
                    // }
                    if (listItem.target.className.indexOf('second') !== -1) {
                        if (methodUseId.indexOf(listItem.target.id) === -1) {
                            methodUseId.push(listItem.target.id);
                            methodUse.push(listItem.target.innerText);
                        }
                    }
                }
                // let nodes = [];
                // for (let i = 0; i < methodUseId.length; i++) {
                //     let nodeParam = {};
                //     nodeParam.taskId = methodUseId[i];
                //     nodeParam.artifactId = methodUse[i];
                //     nodeParam.params = this.totalModelParam[i];
                //     nodes.push(nodeParam);
                // }
                // console.log(nodes);
                //拼接参数
                let runParam = {};
                runParam.dagName = new Date().getTime();
                runParam.dagId = methodUse[0] + new Date().getTime();
                runParam.connections = methodUseId.toString();
                runParam.nodes = this.totalModelParam;

                // console.log(runParam);
                // this.dagId=runParam.dagId;
                for (let paramNeed of runParam.nodes) {
                    debugger;
                    if (paramNeed.params == undefined) {
                        this.$message({
                            type: 'warning',
                            message: '请填写全部所需参数'
                        })
                    }else if(paramNeed.params.length >0){
                        debugger;
                        //监控列表参数的赋值
                        // this.tableData = methodUse;
                        let that = this;
                        this.$axios.post('/wf/post',runParam).then(function (response) {
                            that.$message({
                                type: 'success',
                                message: '提交运行成功'
                            });
                            debugger;
                            that.tableData = runParam.dagId;
                            that.dagId.push(runParam.dagId);
                            runParam = {};
                            that.totalModelParam = [];
                        }).catch(function (error) {
                            that.$message({
                                type: 'warning',
                                message: '运行失败，请检查'
                            });
                            console.log(error)
                        });
                        break;
                    }
                }
            },
            addGeeMap(mapData){
                let that=this;
                that.$axios.get(mapData).then(
                    function (res) {
                        if (res.body) {
                            let vectorLayer = new ol.layer.Vector({
                                source: new ol.source.Vector({
                                    features: new ol.format.GeoJSON().readFeatures(res.body, {
                                        dataProjection: 'EPSG:4326',    // 设定JSON数据使用的坐标系
                                        featureProjection: 'EPSG:3857' // 设定当前地图使用的feature的坐标系
                                    })
                                }),
                                style: that.styleInit
                            });
                            let extent = ol.proj.transformExtent(res.body.bbox, 'EPSG:4326', 'EPSG:3857');
                            that.map.getView().fit(extent, that.map.getSize());//视图更新到当前图层的bbox
                            that.map.addControl(new ol.control.ZoomToExtent({
                                extent: extent,
                                className: "custom-zoom-extent"
                            }));//增加缩放到当前图层控件
                            that.map.addLayer(vectorLayer);
                            return vectorLayer;
                        }
                        else {
                            that.$Bus.$emit("alertModalParams", {
                                alertType: "warning",
                                alertDescription: "该数据为空"
                            });
                            return null;
                        }
                    }).catch(function (err) {
                    console.log(err)
                })
            },
            //自定义图层样式
            styleInit(feature) {
                //TODO:其他geometry的样式需要美化
                let geometryType = feature.getGeometry().getType()
                switch (geometryType) {
                    case "Point":
                        if (Object.keys(feature.values_).indexOf("ClusterID") !== -1) {
                            return this.clazzStyle(feature.values_.ClusterID);
                        } else {
                            return new ol.style.Style({
                                image: new ol.style.Circle({
                                    radius: 7,
                                    fill: new ol.style.Fill({
                                        color: 'red'
                                    })
                                })
                            });
                        }
                    case "LineString":
                        return this.lineStyle(feature);
                    case "MultiLineString":
                        return this.lineStyle(feature);
                    case "MultiPoint":
                        return new ol.style.Style({
                            fill: new ol.style.Fill({color: '#e6a299'}), //填充
                            stroke: new ol.style.Stroke({
                                color: 'rgb(165,24,27)',
                                width: 3,
                                lineDash: [10, 10]
                            })
                        });
                    case "MultiPolygon":
                        return new ol.style.Style({
                            stroke: new ol.style.Stroke({
                                color: 'yellow',
                                width: 1
                            }),
                            fill: new ol.style.Fill({
                                color: 'rgba(255, 255, 0, 0.5)'
                            })
                        });
                    case "Polygon":
                        return new ol.style.Style({
                            stroke: new ol.style.Stroke({
                                color: 'blue',
                                lineDash: [4],
                                width: 3
                            }),
                            fill: new ol.style.Fill({
                                color: 'rgba(0, 0, 255, 0.1)'
                            })
                        });
                    case "GeometryCollection":
                        return new ol.style.Style({
                            stroke: new ol.style.Stroke({
                                color: 'magenta',
                                width: 2
                            }),
                            fill: new ol.style.Fill({
                                color: 'magenta'
                            }),
                            image: new ol.style.Circle({
                                radius: 10,
                                fill: null,
                                stroke: new ol.style.Stroke({
                                    color: 'magenta'
                                })
                            })
                        });
                    case "Circle":
                        return new ol.style.Style({
                            stroke: new ol.style.Stroke({
                                color: 'red',
                                width: 2
                            }),
                            fill: new ol.style.Fill({
                                color: 'rgba(255,0,0,0.2)'
                            })
                        });
                    default:
                        return null;
                }
            },
            //线样式编辑器
            lineStyle(feature) {
                let geometry = feature.getGeometry();
                let styles = [
                    new ol.style.Style({
                        fill: new ol.style.Fill({
                            color: '#ff9f64'
                        }),
                        stroke: new ol.style.Stroke({
                            width: 3,
                            color: '#94c0ff',
                            lineDash: [6],
                        })
                    })
                ];
                geometry.forEachSegment(function (start, end) {
                    let endLonLat = [end[0], end[1]];
                    let startLonLat = [start[0], start[1]];
                    styles.push(new ol.style.Style({
                        geometry: new ol.geom.Point(endLonLat),
                        image: new ol.style.Circle({
                            radius: 5,
                            fill: new ol.style.Fill({
                                color: '#f88b7b'
                            })
                        })
                    }));
                    styles.push(new ol.style.Style({
                        geometry: new ol.geom.Point(startLonLat),
                        image: new ol.style.Circle({
                            radius: 5,
                            fill: new ol.style.Fill({
                                color: '#9bcd5d'
                            })
                        })
                    }));
                });
                return styles;
            },
            clazzStyle(clazz) {
                if (clazz == 0) {
                    return new ol.style.Style({
                        image: new ol.style.Circle({
                            radius: 7,
                            fill: new ol.style.Fill({
                                color: '#3a83d7'
                            })
                        })
                    });
                } else if (clazz == 1) {
                    return new ol.style.Style({
                        image: new ol.style.Circle({
                            radius: 7,
                            fill: new ol.style.Fill({
                                color: '#2bd6ff'
                            })
                        })
                    });
                } else if (clazz == 2) {
                    return new ol.style.Style({
                        image: new ol.style.Circle({
                            radius: 7,
                            fill: new ol.style.Fill({
                                color: '#ff9b76'
                            })
                        })
                    });
                } else if (clazz == 3) {
                    return new ol.style.Style({
                        image: new ol.style.Circle({
                            radius: 7,
                            fill: new ol.style.Fill({
                                color: '#ff148c'
                            })
                        })
                    });
                } else if (clazz == 4) {
                    return new ol.style.Style({
                        image: new ol.style.Circle({
                            radius: 7,
                            fill: new ol.style.Fill({
                                color: '#46ff38'
                            })
                        })
                    });
                } else if (clazz == 5) {
                    return new ol.style.Style({
                        image: new ol.style.Circle({
                            radius: 7,
                            fill: new ol.style.Fill({
                                color: '#a851ff'
                            })
                        })
                    });
                }
            },
        },
        mounted() {
            this.showTable();
            this.showMyData();
            this.mapInit();
            this.showModelData();

            let that = this;
            jsPlumb.ready(function () {
                let j_instance = jsPlumb.getInstance({
                    DragOptions: {cursor: "pointer", zIndex: 2000},
                    PaintStyle: {stroke: "#346789", strokeWidth: 1},
                    Endpoint: ["Dot", {radius: 5}],
                    Connector: ["Bezier", {curviness: 70}],
                    ConnectionOverlays: [
                        ["Arrow",
                            {
                                location: 1,
                                visible: true,
                                width: 11,
                                height: 11,
                                id: "Arrow"
                            }
                        ],
                        ["Label",
                            {
                                location: 0.1,
                                id: "Label",
                                cssClass: "arrow-label",
                                events: {
                                    tap() {
                                        console.log("Label");
                                    }
                                }
                            }]
                    ],
                    Container: "flowchart-demo"
                });
                //作为节点可拖动。
                // j_instance.draggable($(".window"), {containment: "flowchart-demo"});
                $("#flowchart-demo").droppable({
                    scope: "inputnodes",
                    drop: function (ev, ui) {
                        let className = '';
                        if (that.selectedTab == 0)
                            className = "windowpane-first";
                        else
                            className = "windowpane-second";

                        // let className = 'window' + $(ui.helper).parents('.el-tab-pane')[0].id;
                        let id = "item" + new Date().getTime();
                        let showFormId = "edit" + id;
                        let showTableId = "table" + id;
                        let html = '';
                        if (className == 'windowpane-first') {
                            html = `<div id="${id}" class="${className}"><span>${ui.helper.text()}<i class=" fa fa-table" id="${showTableId}"></i></span></div>`;
                        } else if (className == 'windowpane-second') {
                            html = `<div id="${id}" class="${className}"><span>${ui.helper.text()}<i class=" fa fa-life-ring" id="${showFormId}"></i></span></div>`;
                        }
                        $(this).append(html);

                        let basetop = $("#flowchart-demo").position().top;
                        let baseleft = $("#flowchart-demo").position().left;

                        $("#" + id).css({
                            top: ui.position.top + basetop + "px",
                            left: ui.position.top - baseleft + "px"
                        });
                        let currentItem = document.getElementById(id);
                        //双击删除自己，以及与自身相关的连线。
                        currentItem.ondblclick = function () {
                            j_instance.remove(id);
                        };
                        //弹出modelForm
                        if (document.getElementById(showFormId)) {
                            document.getElementById(showFormId).onclick = function () {

                                that.dialogVisible.v = true;
                                that.artifactId = $(currentItem)[0].innerText;
                                let currentItemId = document.getElementById(showFormId).parentElement.parentElement.id;
                                that.page = 'gee';
                                that.$Bus.$emit('pop', that.dialogVisible, that.artifactId,currentItemId);
                            };
                        }
                        //弹出数据预览tab页
                        if (document.getElementById(showTableId)) {
                            document.getElementById(showTableId).onclick = function () {
                                console.log(that.previewDialogVisible.v)
                                that.previewDialogVisible.v = true;
                                that.artifactId = $(currentItem)[0].innerText;
                                console.log(this.artifactId)
                                // this.$axios.get('')
                                console.log(that.artifactId);
                                that.page = 'gee';
                                that.$Bus.$emit('dataDialogParams', that.previewDialogVisible, that.artifactId);
                            };
                        }
                        j_instance.draggable(id, {
                            grid: [1, 1],
                            containment: "flowchart-demo"
                        });
                        // j_instance.draggable($("#" + id), { containment: "flowchart-demo" });
                        //maxConnections为-1则不限制其连线的数量，应改为模型对应参数的数量。
                        j_instance.addEndpoint(id, {
                            anchor: "Right",
                            maxConnections: that.maxIn,
                            endpointStyle: {
                                fill: "rgb(33, 194, 33)"
                            },
                            isSource: true
                        });
                        j_instance.addEndpoint(id, {
                            anchor: "Left",
                            maxConnections: that.maxIn,
                            endpointStyle: {
                                fill: "#346789"
                            },
                            isTarget: true
                        });
                    }
                });
                jsPlumb.fire("jsPlumbDemoLoaded", j_instance);
                that.j_instance = j_instance;
            });
        },
        created() {
        },
        watch: {
            totalModelParam: function () {
                console.log(this.totalModelParam);
            },
        }
    }
</script>

<style>
    .ui-clone {
        width: auto;
        height: 35px;
        line-height: 35px;
        text-align: center;
        background-color: #eeeeef;
        border-radius: 0.5em;
        opacity: 0.8;
        padding: 0 25px;
        font-size: 11px;
    }

    .gee {
        height: 600px;
    }

    #top {
        height: 100%;
    }

    .el-col {
        height: 93%;
    }

    .grid-content3 {
        max-height: 400px;
        overflow: auto;
    }

    .grid-content1, .grid-content2, .grid-content3 {
        margin-top: 15px;
        background-color: rgb(255, 255, 255);
        border-radius: 4px;
        height: 100%;
        min-width: 200px;
    }

    .el-tabs__item {
        font-size: 13px !important;
    }

    .el-tabs__nav {
        margin-left: 10px;
    }

    .el-tabs__content {
        height: 78%;
        width: 24.35%;
        position: absolute;
    }

    .el-table td, .el-table th {
        padding: 4px 0 !important;
    }

    .flowchart-demo {
        width: 100%;
        height: 100%;
        /*border: 1px solid #000;*/
        position: absolute;
    }

    .windowpane-first {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        border: 1px solid #346789;
        box-shadow: 2px 2px 19px #aaa;
        -o-box-shadow: 2px 2px 19px #aaa;
        -webkit-box-shadow: 2px 2px 19px #aaa;
        -moz-box-shadow: 2px 2px 19px #aaa;
        -moz-border-radius: 0.5em;
        border-radius: 0.5em;
        opacity: 0.8;
        filter: alpha(opacity=80);
        text-align: center;
        position: absolute;
        background-color: #eeeeef;
        color: black;
        font-family: helvetica;
        font-size: 0.9em;
        line-height: 45px;
        /*width: 120px;*/
        width: auto;
        padding: 0 10px;
        height: 45px;
    }

    .windowpane-second {
        box-shadow: 2px 2px 19px #aaa;
        -o-box-shadow: 2px 2px 19px #aaa;
        -webkit-box-shadow: 2px 2px 19px #aaa;
        -moz-box-shadow: 2px 2px 19px #aaa;
        -moz-border-radius: 50%;
        border-radius: 50%;
        opacity: 0.8;
        filter: alpha(opacity=80);
        border: 1px solid #346789;
        background-color: #eeeeef;
        color: black;
        font-size: 9pt;
        cursor: pointer;
        width: auto;
        height: auto;
        position: absolute;
    }

    .windowpane-second span {
        display: inline-block;
        text-align: center;
        padding: 15px;
    }

    .windowpane-second span i,.windowpane-first span i {
        padding-left: 6px;
    }

    .workspace {
        background-color: rgb(255, 255, 255);
        width: 100%;
        height: 100%;
        /*border: 1px solid rgb(51, 129, 165);*/
        float: left;
        position: relative;
    }

    .butt {
        width: 60px;
        height: 35px;
        bottom: 1.5%;
        position: absolute;
        box-shadow: 2px 2px 19px #aaa;
        -o-box-shadow: 2px 2px 19px #aaa;
    }

    .butt span {
        margin-left: -5px;
    }

    /*.ol-overlaycontainer-stopevent{*/
    /*display: none;*/
    /*}*/
    html {
        overflow: hidden;
    }

</style>